package com.thenie.chat.validator;

import com.thenie.chat.util.ValidatorUtil;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Valid;

/**
 * 邮箱校验规则
 *
 * @author thenie
 * @since 1.0.0
 */
public class IsEmailValidator implements ConstraintValidator<IsEmail,String> {

    //是否必须
    private boolean required = false;

    @Override
    public void initialize(IsEmail constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(!required && StringUtils.isEmpty(value)){
            return true;
        }else{
            if (StringUtils.isEmpty(value))
                return false;
            return ValidatorUtil.isEmail(value);
        }
    }
}